import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/sys/menuBtnManagement/menu'
import Layout from '@/layout/index'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit, state }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters(state.token).then(res => {
          const sdata = JSON.parse(JSON.stringify(res.data.menuVos))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
          const rewriteRoutes = filterAsyncRouter(sdata)
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          // 信用
          rewriteRoutes.push({
            path: '/routerLink',
            name: 'RouterLink',
            component: Layout,
            children: [
              {
                path: 'dispatchLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'dispatchLink',
                meta: { title: 'dispatchLink' }
              },
              {
                path: 'sysLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'sysLink',
                meta: { title: 'sysLink' }
              },
              {
                path: 'gzfwLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'gzfwLink',
                meta: { title: 'gzfwLink' }
              },
              {
                path: 'creditLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'creditLink',
                meta: { title: 'creditLink' }
              },
              {
                path: 'fxjcLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'fxjcLink',
                meta: { title: 'fxjcLink' }
              },
              {
                path: 'monitorLink',
                component: () => import('@/components/RouterLink/RouterLink'),
                name: 'monitorLink',
                meta: { title: 'monitorLink' }
              },
            ]
          })
          // 系统管理
          // rewriteRoutes.push({
          //   path: '/systemLink',
          //   name: 'SystemLink',
          //   component: Layout,
          //   children: [
          //     {
          //       path: 'systemLink',
          //       component: () => import('@/components/RouterLink/RouterLink'),
          //       name: 'systemLink',
          //       meta: { title: 'systemLink' }
          //     }
          //   ]
          // })
          router.addRoutes(asyncRoutes)
          // store.dispatch('assignmentPermissions', res.data.permission)
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          //顶栏路由
          commit(
            'SET_TOPBAR_ROUTES',
            (sdata || [])
              .filter(s => s.hidden == false)
              .sort((s1, s2) => s1.sort - s2.sort)
          )
          resolve(constantRoutes.concat(rewriteRoutes))
        })
      })
    }
  }
}

//  把后台返回菜单组装成routes要求的格式
function filterAsyncRouter(asyncRouterMap, isChildren = false) {
  const res = []
  asyncRouterMap.forEach(route => {
    let newRouter = {}

    let {
      menuPath,
      menuName,
      component,
      alwaysShow,
      permissions,
      meta,
      hidden,
      children,
      classification_dictText,
      classification,
      query
    } = route
    if (component) {
      // Layout 组件特殊处理
      if (component === 'Layout') {
        component = Layout
      } else {
        component = loadView(component)
      }
    }
    //处理不是子菜单的数据
    if (!isChildren) {
      newRouter['alwaysShow'] = alwaysShow
      newRouter['permissions'] = permissions == null ? ['*:*:*'] : permissions
      newRouter['redirect'] = menuPath
      meta['classification_dictText'] = classification_dictText
      meta['classification'] = classification
    }
    //处理是子菜单的数据
    if (isChildren) {
      newRouter['hidden'] = hidden
    }
    newRouter['path'] = menuPath
    newRouter['name'] = menuName
    newRouter['component'] = component
    newRouter['meta'] = meta
    newRouter['query'] = query

    if (children != null && children && children.length) {
      let isChildren = true
      newRouter['children'] = filterAsyncRouter(children, isChildren)
    }
    res.push(newRouter)
  })

  return res
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = view => {
  if (process.env.NODE_ENV === 'development') {
    return resolve => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default permission
